package sources;

import java.io.IOException;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

public class SaveableData {

	public final String sourceName;
	public final String poolName;
	public final byte[] bytes;
	public final int[] rawData;
	
	public SaveableData(String sourceName, String poolName, byte[] bytes, int[] rawData){
		this.sourceName = sourceName;
		this.poolName = poolName;
		this.bytes = bytes;
		this.rawData = rawData;
	}

	private void writeRawData(OutputStream os) throws IOException {
		if(rawData.length == 0){
			return;
		}
		os.write(Integer.toString(rawData[0]).getBytes());
		for(int i = 1; i<rawData.length; i++){
			os.write((", " + rawData[i]).getBytes());
		}
	}

	private void writeRandomBits(OutputStream os) throws IOException {
		for(int byteOffset = 0; byteOffset < bytes.length; byteOffset++){
			int mask = 0x80;
			for(int bitOffset = 0; bitOffset < 8; bitOffset++){
				char bit = (byte)(bytes[byteOffset] & mask) == 0 ? '0' : '1';
				os.write(bit);
				mask = mask >>> 1;
			}
		}
	}
	
	public FileConnection save() throws IOException{
		FileConnection fc =(FileConnection)Connector.open("file:///store/home/user/" + fileName());
		fc.create();
		OutputStream os = fc.openOutputStream();
		os.write(sourceName.getBytes());
		os.write(':');
		os.write(poolName.getBytes());
		os.write(':');
		writeRandomBits(os);
		os.write(':');
		writeRawData(os);
		return fc;
	}

	private String fileName() {
		return (sourceName + "_" + poolName + "_" + System.currentTimeMillis()).replace(' ', '_');
	}
	
	public String toString(){
		return sourceName + ":" + poolName + ":" + randomBitString() + ":" + rawDataString();
	}

	private String rawDataString() {
		if(rawData.length == 0){
			return "";
		}
		String raw = Integer.toString(rawData[0]);
		for(int i = 1; i<rawData.length; i++){
			raw += ", " + rawData[i];
		}
		return raw;
	}

	private String randomBitString() {
		char[] asciiBits = new char[bytes.length * 8];
		for(int byteOffset = 0; byteOffset < bytes.length; byteOffset++){
			int mask = 0x80;
			for(int bitOffset = 0; bitOffset < 8; bitOffset++){
				char bit = (byte)(bytes[byteOffset] & mask) == 0 ? '0' : '1';
				asciiBits[byteOffset * 8 + bitOffset] = bit;
				mask = mask >> 1;
			}
		}
		return new String(asciiBits);
	}
}
